package jmine.tec.persist.schema.impl.parsers;

import java.util.regex.Matcher;

import jmine.tec.persist.schema.api.IndexOrder;
import jmine.tec.persist.schema.impl.elements.IndexElement;
import jmine.tec.persist.schema.impl.elements.Schema;

/**
 * Parser de índices
 * 
 * @author lundberg
 */
public class IndexParser extends AbstractSchemaElementParser<IndexElement> {

    private static final int INDEX_NAME_GROUP_INDEX = 1;

    private static final int TABLE_NAME_GROUP_INDEX = 2;

    private static final int COLUMNS_GROUP_INDEX = 3;

    /**
     * Construtor
     * @param schema schema
     */
    public IndexParser(Schema schema) {
        super("create\\s+index\\s+(\\w+)\\s+on\\s+(\\w+)\\s+\\(([\\w\\s,]+)\\)", schema);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IndexElement doParse(Matcher matcher) {
        String name = matcher.group(INDEX_NAME_GROUP_INDEX);
        String table = matcher.group(TABLE_NAME_GROUP_INDEX);
        IndexElement index = new IndexElement(table, name, getSchema());
        for (String col : matcher.group(COLUMNS_GROUP_INDEX).trim().split("\\s*,\\s*")) {
            String[] split = col.split("\\s+");
            String column = split[0];
            if (split.length == 1) {
                index.addColumn(col);
            } else {
                if (split[1].equalsIgnoreCase("asc")) {
                    index.addColumn(column, IndexOrder.ASC);
                } else if (split[1].equalsIgnoreCase("desc")) {
                    index.addColumn(column, IndexOrder.DESC);
                } else {
                    throw new IllegalStateException();
                }
            }
        }
        return index;
    }

}
